#include <string>
#include <cstring>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <functional>
#include "log.hpp"

Log lg;

const int size = 4096;
const uint16_t defaultport = 8080;
const std::string defaultip = "113.45.60.212";

using func_t = function<std::string(std::string)>;

class UdpServer
{
public:
    UdpServer(const uint16_t &port = defaultport, const std::string &ip = defaultip) : _ip(ip), _port(port), _sockfd(0), _isrunning(false)
    {}

    void init()
    {
        _sockfd = socket(AF_INET, SOCK_DGRAM, 0);
        if(socket < 0)
        {
            lg(FATAL, "socket fail, errno: %d, strerror: %s", errno, strerror(errno));
            exit(0);
        }
        lg(INFO, "socket success, sockfd: %d, errno: %d, strerror: %s", _sockfd, errno, strerror(errno));

        struct sockaddr_in Server;
        //清空Server
        bzero(&Server, sizeof(Server));
        Server.sin_family = AF_INET;
        Server.sin_addr.s_addr = inet_addr(_ip.c_str()); //将字符串风格的ip转化为uint64_t类型的整型
        Server.sin_port = htons(_port);

        socklen_t len = sizeof(Server);
        if(bind(_sockfd, (struct sockaddr *)&Server, len) < 0)
        {
            lg(FATAL, "bind fail, errno: %d, strerror: %s", errno, strerror(errno));
            exit(0);
        }
        lg(INFO, "bind success, errno: %d, strerror: %s", errno, strerror(errno));
        
    }

    void Run(func_t fun)
    {
        char buffer[size];
        
        while(true)
        {
            struct sockaddr_in Client;
            socklen_t len = sizeof(Client);
            ssize_t s = recvfrom(_sockfd, buffer, size, 0, (struct sockaddr*)&Client, &len);
            if(s < 0)
            {
                lg(WARNING, "recvfrom fail, errno: %d, strerror: %d\n", errno, strerror(errno));
                continue;
            }

            buffer[s] = 0;
            std::string message = buffer;
            std::string echo_string = fun(message);

            sendto(_sockfd, echo_string.c_str(), echo_string.size(), 0, (struct sockaddr *)&Client, len);
        }
    }

    ~UdpServer()
    {
        if(_sockfd > 0) close(_sockfd);
    }
private:
    uint16_t _port;
    std::string _ip;
    int _sockfd;
    bool _isrunning;
};